/************************************************************************************/
/*  Program name CAPPOIMP_ORG_STRUCT_VERSION.sql                                */
/*  Creater:  CHAN BILLY KA KEUNG (PCCW - UniHub)                                   */
/*************   History   *************************                                */
/* 24 MAY 2006				       First created                                    */
/************************************************************************************/
SET SERVEROUTPUT ON SIZE 1000000;

DECLARE
	lv_Prog_ID		VARCHAR2(100)	:=	'CAPPOIMP_ORG_STRUCT_VERSION';

	lv_Scc_Count	NUMBER	:=	0;
	lv_Err_Count	NUMBER	:=	0;
	lv_Err_Msg		VARCHAR2(500)	:=	'No Error';

	lv_seq_id		NUMBER;
	
	CURSOR Cur_F IS
	SELECT
		*
	FROM
		CRST_PO_ORG_STRUCT_VERSION
	FOR UPDATE;
		
	
BEGIN
	FOR C1 IN Cur_F LOOP
		BEGIN
			
			SELECT PER_ORG_STRUCTURE_VERSIONS_S.NEXTVAL
			INTO lv_seq_id
			FROM DUAL;
			
			UPDATE CRST_PO_ORG_STRUCT_VERSION
			SET ORG_STRUCTURE_VERSION_ID_N = lv_seq_id
			WHERE ORG_STRUCTURE_VERSION_ID = C1.ORG_STRUCTURE_VERSION_ID;
						
			INSERT INTO PER_ORG_STRUCTURE_VERSIONS
			VALUES
			(
			lv_seq_id,
			CAPBRIMP_MAPPING.GetBGMapping(C1.BUSINESS_GROUP_ID),
			CAPPOIMP_MAPPING.GetOrgStructureMapping(C1.ORGANIZATION_STRUCTURE_ID),
			C1.DATE_FROM                     ,
			C1.VERSION_NUMBER                ,
			C1.COPY_STRUCTURE_VERSION_ID     ,
			C1.DATE_TO                       ,
			C1.REQUEST_ID                    ,
			C1.PROGRAM_APPLICATION_ID        ,
			C1.PROGRAM_ID                    ,
			C1.PROGRAM_UPDATE_DATE           , 
			C1.LAST_UPDATE_DATE              , 
			C1.LAST_UPDATED_BY               ,
			C1.LAST_UPDATE_LOGIN             ,
			C1.CREATED_BY                    ,
			C1.CREATION_DATE                 ,
			C1.OBJECT_VERSION_NUMBER         ,
			C1.TOPNODE_POS_CTRL_ENABLED_FLAG 
			);
		EXCEPTION
			WHEN OTHERS THEN
				DBMS_OUTPUT.Put_Line(SQLERRM);
				lv_Err_Count	:=	lv_Err_Count + 1;
		END;
		lv_Scc_Count	:=	lv_Scc_Count	+	1;
	END LOOP;

	IF	lv_Err_Count	>	0	THEN
		ROLLBACK;
	END IF;
	
	INSERT INTO CAPCNV_LOG(
		PROG_ID,
		PROCESS_DATE,
		RECORD_PROCESSED,
		RECORD_REJECTED,
		RECORD_EXTRACTED,
		ERR_MSG
	) VALUES (
		lv_Prog_ID,
		SYSDATE,
		lv_Scc_Count,
		lv_Err_Count,
		lv_Scc_Count-lv_Err_Count,
		lv_Err_Msg
	);
	
	COMMIT;
END;
/

